package com.dy.org.service.impl;

import com.dy.basic.service.impl.BaseServiceImpl;
import com.dy.org.domain.Department;
import com.dy.org.domain.Employee;
import com.dy.org.mapper.DepartmentMapper;
import com.dy.org.service.DepartmentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> findDepartmentTree() {
        List<Department> deptAll = departmentMapper.findAll();
        Map<Long, Department> allMap = deptAll.stream().collect(Collectors.toMap(Department::getId, item -> item));
        ArrayList<Department> depts = new ArrayList<>();
        for (Department first: deptAll ) {
            if (first.getParentId() == null){
                depts.add(first);
            }else {
                Department department = allMap.get(first.getParentId());
                if (department != null){
                    department.getChildren().add(first);
                }
            }
        }
        return depts;
    }

    /**
     * 获取员工的信息
     * @param id
     * @return
     */
    @Override
    public List<Employee> findEmpById(Long id) {
        return departmentMapper.findEmpById(id);
    }

}
